#include "doctorwidget.h"
#include "ui_doctorwidget.h"
#include "doctorprofilewidget.h"
#include "appointmentwidget.h"
#include "../common/patientdetailwidget.h"
#include "medicalrecordwidget.h"
#include "prescriptionwidget.h"
#include "doctor_chatlistwidget.h"
#include "attendancewidget.h"
#include "../../network/networkclient.h"
#include <QMessageBox>
#include <QTimer>
#include <functional>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
#include <QBrush>
#include <QColor>

DoctorWidget::DoctorWidget(const Doctor& doctor, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DoctorWidget),
    m_doctor(doctor),
    m_notificationList(nullptr),
    m_currentPatientId(0),
    m_currentAppointmentId(0),
    m_unreadNotificationCount(0)
{
    ui->setupUi(this);
    
    // 连接网络信号
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &DoctorWidget::onMessageReceived);
    
    // 加载医生信息
    loadDoctorInfo();
    
    // 默认显示个人中心（首次登录完善信息）
    on_profileTab_clicked();
}

DoctorWidget::~DoctorWidget() {
    delete ui;
}

void DoctorWidget::loadDoctorInfo() {
    // 请求医生详细信息
    QJsonObject request;
    request["user_id"] = m_doctor.id;
    NetworkClient::instance().sendRequest(MSG_GET_DOCTOR_INFO, request);
}

void DoctorWidget::on_profileTab_clicked() {
    // 设置按钮选中状态
    ui->profileTab->setChecked(true);
    ui->appointmentsTab->setChecked(false);
    ui->chatTab->setChecked(false);
    ui->attendanceTab->setChecked(false);
    
    // 清空当前内容
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    // 创建个人信息编辑界面
    DoctorProfileWidget *widget = new DoctorProfileWidget(m_doctor, this);
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::on_appointmentsTab_clicked() {
    // 设置按钮选中状态
    ui->profileTab->setChecked(false);
    ui->appointmentsTab->setChecked(true);
    ui->chatTab->setChecked(false);
    ui->attendanceTab->setChecked(false);
    
    // 清空当前内容
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    // 创建预约列表界面
    AppointmentWidget *widget = new AppointmentWidget(m_doctor, this);
    
    // 连接查看患者详情信号
    connect(widget, &AppointmentWidget::showPatientDetail,
            this, &DoctorWidget::showPatientDetail);
    
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::showPatientDetail(int patientId, int appointmentId) {
    // 保存当前患者和预约ID
    m_currentPatientId = patientId;
    m_currentAppointmentId = appointmentId;
    
    // 清空当前内容
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    // 创建患者详情界面
    PatientDetailWidget *widget = new PatientDetailWidget(m_doctor, patientId, appointmentId, this);
    
    // 连接返回信号
    connect(widget, &PatientDetailWidget::backToAppointments,
            this, &DoctorWidget::on_appointmentsTab_clicked);
    
    // 连接创建病历和处方信号
    connect(widget, &PatientDetailWidget::showCreateRecord,
            this, &DoctorWidget::showCreateRecord);
    connect(widget, &PatientDetailWidget::showCreatePrescription,
            this, &DoctorWidget::showCreatePrescription);
    
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::showCreateRecord(const Doctor& doctor, const Patient& patient, int appointmentId, const QDateTime& appointmentTime) {
    // 清空当前内容
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    // 创建病历编辑界面（带预约ID和预约时间）
    MedicalRecordWidget *widget = new MedicalRecordWidget(doctor, patient, appointmentId, appointmentTime, this);
    
    // 连接病历创建成功信号，返回患者详情
    connect(widget, &MedicalRecordWidget::recordCreated,
            [this]() {
                // 重新加载患者详情页，使用保存的ID
                showPatientDetail(m_currentPatientId, m_currentAppointmentId);
            });
    
    // 连接返回按钮信号
    connect(widget, &MedicalRecordWidget::backToPatientDetail,
            [this]() {
                showPatientDetail(m_currentPatientId, m_currentAppointmentId);
            });
    
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::showCreatePrescription(const Doctor& doctor, const Patient& patient, int appointmentId, int latestRecordId) {
    // 清空当前内容
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    // 创建处方编辑界面（带预约ID和病历ID）
    PrescriptionWidget *widget = new PrescriptionWidget(doctor, patient, appointmentId, latestRecordId, this);
    
    // 连接处方创建成功信号，返回患者详情
    connect(widget, &PrescriptionWidget::prescriptionCreated,
            [this]() {
                // 重新加载患者详情页，使用保存的ID
                showPatientDetail(m_currentPatientId, m_currentAppointmentId);
            });
    
    // 连接返回按钮信号
    connect(widget, &PrescriptionWidget::backToPatientDetail,
            [this]() {
                showPatientDetail(m_currentPatientId, m_currentAppointmentId);
            });
    
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::on_chatTab_clicked() {
    // 设置按钮选中状态
    ui->profileTab->setChecked(false);
    ui->appointmentsTab->setChecked(false);
    ui->chatTab->setChecked(true);
    ui->attendanceTab->setChecked(false);
    
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    DoctorChatListWidget *widget = new DoctorChatListWidget(m_doctor.id, this);
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::on_attendanceTab_clicked() {
    // 设置按钮选中状态
    ui->profileTab->setChecked(false);
    ui->appointmentsTab->setChecked(false);
    ui->chatTab->setChecked(false);
    ui->attendanceTab->setChecked(true);
    
    QWidget *oldWidget = ui->contentArea->widget();
    if (oldWidget) {
        ui->contentArea->takeWidget();
        oldWidget->deleteLater();
    }
    
    AttendanceWidget *widget = new AttendanceWidget(m_doctor, this);
    connect(widget, &AttendanceWidget::backToMain, this, &DoctorWidget::on_appointmentsTab_clicked);
    ui->contentArea->setWidget(widget);
}

void DoctorWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_DOCTOR_INFO_RESPONSE) {
        if (data["success"].toBool()) {
            m_doctor.departmentId = data["department_id"].toInt();
            m_doctor.departmentName = data["department_name"].toString();
            m_doctor.title = data["title"].toString();
            m_doctor.specialty = data["specialty"].toString();
            
            // 更新界面显示
            ui->doctorNameLabel->setText(m_doctor.realName);
            ui->departmentLabel->setText(m_doctor.departmentName);
            ui->titleLabel->setText(m_doctor.title);
        }
    } else if (type == MSG_GET_NOTIFICATIONS_RESPONSE) {
        if (data["success"].toBool()) {
            updateNotificationList(data["notifications"].toArray());
        }
    }
}

void DoctorWidget::updateNotificationList(const QJsonArray& notifications) {
    if (!m_notificationList) return;
    
    m_notificationList->clear();
    
    if (notifications.isEmpty()) {
        QListWidgetItem* emptyItem = new QListWidgetItem(m_notificationList);
        emptyItem->setText("📭 暂无通知");
        emptyItem->setTextAlignment(Qt::AlignCenter);
        emptyItem->setForeground(QBrush(QColor("#999999")));
        return;
    }
    
    for (const QJsonValue& value : notifications) {
        QJsonObject notifObj = value.toObject();
        QString title = notifObj["title"].toString();
        QString content = notifObj["content"].toString();
        QString createTime = notifObj["create_time"].toString();
        
        QString displayText = QString("%1\n%2\n时间：%3")
            .arg(title, content, createTime);
        
        QListWidgetItem* item = new QListWidgetItem(m_notificationList);
        item->setText(displayText);
        item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        item->setForeground(QBrush(QColor("#333333")));
    }
}

void DoctorWidget::on_notificationButton_clicked() {
    // 创建通知列表Widget
    QWidget* notificationWidget = new QWidget(this);
    QVBoxLayout* layout = new QVBoxLayout(notificationWidget);
    
    // 顶部栏：标题 + 返回按钮
    QHBoxLayout* topLayout = new QHBoxLayout();
    QLabel* titleLabel = new QLabel("通知中心", notificationWidget);
    titleLabel->setStyleSheet("font-size: 20px; font-weight: bold; color: #409EFF; padding: 10px;");
    topLayout->addWidget(titleLabel);
    topLayout->addStretch();
    
    QPushButton* backButton = new QPushButton("← 返回", notificationWidget);
    backButton->setStyleSheet(
        "QPushButton { background-color: #409EFF; color: white; padding: 8px 16px; "
        "border-radius: 6px; font-weight: bold; }"
        "QPushButton:hover { background-color: #66B1FF; }");
    connect(backButton, &QPushButton::clicked, this, &DoctorWidget::on_profileTab_clicked);
    topLayout->addWidget(backButton);
    
    layout->addLayout(topLayout);
    
    // 通知列表
    m_notificationList = new QListWidget(notificationWidget);
    m_notificationList->setStyleSheet(
        "QListWidget { background-color: white; border: 1px solid #E0E0E0; border-radius: 8px; padding: 5px; }"
        "QListWidget::item { background-color: #F7F7F7; border-radius: 6px; padding: 12px; margin: 5px; color: #333333; font-size: 14px; }"
        "QListWidget::item:hover { background-color: #E3F2FD; }"
        "QListWidget::item:selected { background-color: #E3F2FD; color: #000000; }"
    );
    layout->addWidget(m_notificationList);
    
    // 底部按钮
    QHBoxLayout* bottomLayout = new QHBoxLayout();
    QPushButton* clearButton = new QPushButton("清空所有通知", notificationWidget);
    clearButton->setStyleSheet(
        "QPushButton { background-color: #F44336; color: white; padding: 10px; "
        "border-radius: 6px; font-weight: bold; }"
        "QPushButton:hover { background-color: #E53935; }");
    connect(clearButton, &QPushButton::clicked, [this]() {
        QJsonObject request;
        NetworkClient::instance().sendRequest(MSG_CLEAR_ALL_NOTIFICATIONS, request);
        if (m_notificationList) {
            m_notificationList->clear();
        }
        QMessageBox::information(this, "提示", "所有通知已清空");
    });
    bottomLayout->addStretch();
    bottomLayout->addWidget(clearButton);
    bottomLayout->addStretch();
    
    layout->addLayout(bottomLayout);
    
    // 显示通知Widget
    ui->contentArea->setWidget(notificationWidget);
    
    // 请求通知列表
    QJsonObject request;
    NetworkClient::instance().sendRequest(MSG_GET_NOTIFICATIONS, request);
}

